<template>
  <div class="activity-timeline">
    <div class="timeline-header">
      <el-icon class="timeline-icon"><Calendar /></el-icon>
      <span class="timeline-title">活动时间线</span>
    </div>
    
    <div
      class="timeline-content"
      v-loading="loading"
      ref="scrollContainer"
    >
      <div class="timeline-wrapper">
        <!-- 固定头部区域 -->
        <div class="fixed-headers">
          <!-- 左上角区域 -->
          <div class="corner-header">
            <div class="corner-label">区服 / 日期</div>
          </div>
          
          <!-- 日期头部 -->
          <div class="date-header">
            <div 
              v-for="date in dateRange" 
              :key="date.key"
              class="date-cell"
              :class="{ 'today': date.isToday }"
              :style="{ width: cellWidth + 'px', height: headerHeight + 'px' }"
            >
              <div class="date-main">{{ date.day }}</div>
              <div class="date-sub">{{ date.weekday }}</div>
            </div>
          </div>
        </div>
        
        <!-- 滚动内容区域 -->
        <div class="scroll-content" :style="contentStyle">
          <!-- 区服列表（固定左侧） -->
          <div class="servers-sidebar" :style="sidebarStyle">
            <div 
              v-for="server in displayServers" 
              :key="server.key"
              class="server-info"
              :style="{ height: Math.max(80, 20 * getAllActivitiesForServer(server).length) + 'px' }"
            >
              <div class="server-square" :style="{ backgroundColor: getServerColor(server) }">
                <span class="server-id">{{ server.zone_id }}</span>
              </div>
              <div class="server-details">
                <div class="server-name">{{ server.platform }}_{{ server.zone_id }}</div>
                <div class="server-meta">开服: {{ formatDate(server.open_time) }}</div>
                <div class="server-activities">活动: {{ getServerActivityCount(server) }} 个</div>
              </div>
            </div>
          </div>
          
          <!-- 活动网格 -->
          <div class="activity-grid">
            <div 
              v-for="server in displayServers" 
              :key="server.key"
              class="server-row"
              :style="{ height: Math.max(80, 20 * getAllActivitiesForServer(server).length) + 'px' }"
            >
              <!-- 活动横线 - 直接在服务器行中定位 -->
              <div
                v-for="(activity, activityIndex) in getAllActivitiesForServer(server)"
                :key="`${activity.camp_id}-${activityIndex}`"
                class="activity-bar"
                :style="getActivityBarStyle(activity, activityIndex)"
                :title="getActivityTooltip(activity)"
                @click="showActivityDetail(activity)"
              >
                <span class="activity-name">{{ activity.camp_id }}_{{ activity.camp_name }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <el-empty 
        v-if="!loading && (!campData || campData.length === 0)"
        description="暂无活动数据"
        :image-size="120"
        class="empty-state"
      >
        <el-button type="primary" @click="$emit('refresh')">
          刷新数据
        </el-button>
      </el-empty>
    </div>
    
    <!-- 图例 -->
    <div v-if="!loading && campData && campData.length > 0" class="timeline-legend">
      <div class="legend-title">活动类型</div>
      <div class="legend-items">
        <div
          v-for="(color, campName) in activityColorMap"
          :key="campName"
          class="legend-item"
          :class="{ 'hidden-activity': hiddenActivities.includes(campName) }"
          @click="toggleActivityVisibility(campName)"
        >
          <div 
            class="legend-color" 
            :style="{ backgroundColor: color }"
          ></div>
          <span class="legend-text">{{ campName }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { logger } from './utils/logger.ts'
import { Calendar } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  campData: {
    type: Array,
    default: () => []
  },
  selectedServers: {
    type: Array,
    default: () => []
  },
  startTime: {
    type: Date,
    default: null
  },
  endTime: {
    type: Date,
    default: null
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['refresh', 'activity-click'])

// 响应式数据
const scrollContainer = ref(null)
const cellWidth = ref(100)
const cellHeight = ref(80)
const headerHeight = ref(60)
const sidebarWidth = ref(200)
const hiddenActivities = ref<string[]>([]) // 存储被隐藏的活动名称列表

// 服务器颜色映射
const serverColors = [
  '#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F',
  '#BB8FCE', '#85C1E2', '#F8B739', '#52B788', '#E74C3C', '#3498DB'
]

// 活动颜色映射
const activityColors = [
  '#FF4757', '#2ED573', '#1E90FF', '#FFA502', '#FF6348', '#7B68EE',
  '#20BF6B', '#FA8231', '#0FB9B1', '#F8B500', '#6C5CE7', '#A55EEA'
]

// 计算属性
const dateRange = computed(() => {
  const dates = []
  const start = props.startTime || getDefaultStartTime()
  const end = props.endTime || getDefaultEndTime()
  
  const current = new Date(start)
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  
  while (current <= end) {
    const dateObj = new Date(current)
    const isToday = dateObj.getTime() === today.getTime()
    
    dates.push({
      key: dateObj.toISOString().split('T')[0],
      date: new Date(dateObj),
      day: dateObj.getDate().toString().padStart(2, '0'),
      weekday: ['日', '一', '二', '三', '四', '五', '六'][dateObj.getDay()],
      isToday
    })
    
    current.setDate(current.getDate() + 1)
  }
  
  return dates
})

const displayServers = computed(() => {
  return props.selectedServers.map((server: any, index: number) => ({
    ...server,
    key: `${server.platform}_${server.zone_id}`,
    colorIndex: index % serverColors.length
  }))
})

const activityColorMap = computed(() => {
  const colorMap: Record<string, string> = {}
  const uniqueActivities = new Set<string>()
  
  props.campData.forEach((activity: any) => {
    uniqueActivities.add(activity.camp_name)
  })
  
  Array.from(uniqueActivities).forEach((activityName: string, index: number) => {
    colorMap[activityName] = activityColors[index % activityColors.length]
  })
  
  return colorMap
})

// 网格高度计算属性
const gridHeight = computed(() => {
  const defaultMinHeight = 400 // 默认最小高度
  let totalHeight = headerHeight.value // 加上头部高度

  // 计算所有服务器的实际高度总和
  displayServers.value.forEach((server: any) => {
    const activities = getAllActivitiesForServer(server)
    const serverHeight = Math.max(80, 20 * activities.length)
    totalHeight += serverHeight
  })
  return Math.max(defaultMinHeight, totalHeight)
})

// 内容区域样式 - 现在由timeline-content控制高度
const contentStyle = computed(() => ({
  // 移除minHeight，让内容自由扩展
}))

// 服务器边栏样式
const sidebarStyle = computed(() => ({
  border: '3px solid rgba(255, 255, 255, 0.1)',
  
  height: gridHeight.value + 'px'
}))


// 方法
const getDefaultStartTime = () => {
  const date = new Date()
  date.setDate(date.getDate() - 6)
  date.setHours(0, 0, 0, 0)
  return date
}

const getDefaultEndTime = () => {
  const date = new Date()
  date.setDate(date.getDate() + 6)
  date.setHours(23, 59, 59, 999)
  return date
}

const getServerColor = (server: any) => {
  return serverColors[server.colorIndex]
}

const formatDate = (timestamp: any) => {
  if (!timestamp || timestamp === 0) return '未知'
  try {
    return new Date(parseInt(timestamp) * 1000).toLocaleDateString('zh-CN')
  } catch {
    return '无效时间'
  }
}

const getActivitiesForServerAndDate = (server: any, date: any) => {
  const serverKey = server.key
  const dateStart = new Date(date.date)
  const dateEnd = new Date(date.date)
  dateEnd.setHours(23, 59, 59, 999)
  
  logger.debug(`🔍 [活动查找] 查找服务器 ${serverKey} 在 ${date.key} 的活动`)
  logger.debug(`📋 [活动查找] 当前可用活动数据:`, props.campData.map((a: any) => ({ 
    server: a.server, 
    name: a.camp_name,
    start: new Date(a.start_time * 1000).toLocaleDateString('zh-CN'),
    end: new Date(a.end_time * 1000).toLocaleDateString('zh-CN')
  })))
  
  const activities = props.campData.filter((activity: any) => {
    // 更灵活的服务器匹配逻辑
    const activityServer = activity.server || ''
    const isServerMatch = activityServer === serverKey || 
                         activityServer.includes(serverKey) || 
                         serverKey.includes(activityServer)
    
    if (!isServerMatch) {
      return false
    }
    
    const activityStart = new Date(activity.start_time * 1000)
    const activityEnd = new Date(activity.end_time * 1000)
    
    // 检查活动是否与当前日期有重叠
    const hasOverlap = activityStart <= dateEnd && activityEnd >= dateStart
    
    if (hasOverlap) {
      logger.debug(`✅ [活动匹配] ${activity.camp_name} 在 ${serverKey} 的 ${date.key}`, {
        活动服务器: activityServer,
        目标服务器: serverKey,
        活动开始: activityStart.toLocaleString('zh-CN'),
        活动结束: activityEnd.toLocaleString('zh-CN'),
        日期范围: `${dateStart.toLocaleString('zh-CN')} - ${dateEnd.toLocaleString('zh-CN')}`
      })
    }
    
    return hasOverlap
  })
  
  logger.debug(`📊 [活动结果] 服务器 ${serverKey} 在 ${date.key} 有 ${activities.length} 个活动`)
  return activities
}

const getServerActivityCount = (server: any) => {
  const serverKey = server.key
  const count = props.campData.filter((activity: any) => activity.server === serverKey).length
  return count
}

const getAllActivitiesForServer = (server: any) => {
  const serverKey = server.key

  return props.campData.filter((activity: any) => {
    // 更灵活的服务器匹配逻辑
    const activityServer = activity.server || ''
    // const isServerMatch = activityServer === serverKey ||
    //                      activityServer.includes(serverKey) ||
    //                      serverKey.includes(activityServer)
    const isServerMatch = activityServer === serverKey
    // 过滤掉被隐藏的活动
    const isNotHidden = !hiddenActivities.value.includes(activity.camp_name)

    return isServerMatch && isNotHidden
  })
}

const getActivityBarStyle = (activity: any, activityIndex: number) => {
  const activityStart = new Date(activity.start_time * 1000)
  const activityEnd = new Date(activity.end_time * 1000)

  logger.debug(`🎨 [样式计算] 活动 ${activity.camp_name}:`, {
    活动开始: activityStart.toLocaleString('zh-CN'),
    活动结束: activityEnd.toLocaleString('zh-CN')
  })

  // 获取时间轴的开始和结束时间
  const timelineStart = dateRange.value[0]?.date
  const timelineEnd = dateRange.value[dateRange.value.length - 1]?.date

  if (!timelineStart || !timelineEnd) {
    return {
      display: 'none'
    }
  }

  const timelineStartTime = new Date(timelineStart)
  const timelineEndTime = new Date(timelineEnd)
  timelineEndTime.setHours(23, 59, 59, 999)

  // 确保活动在时间轴范围内
  const visibleStart = Math.max(activityStart.getTime(), timelineStartTime.getTime())
  const visibleEnd = Math.min(activityEnd.getTime(), timelineEndTime.getTime())

  // 如果活动完全不在可见范围内，隐藏
  if (visibleStart >= visibleEnd) {
    return {
      display: 'none'
    }
  }

  const timelineDuration = timelineEndTime.getTime() - timelineStartTime.getTime()
  const activityDuration = visibleEnd - visibleStart

  // 计算活动在时间轴上的位置和宽度
  const startOffset = visibleStart - timelineStartTime.getTime()
  const startPercent = (startOffset / timelineDuration) * 100
  const widthPercent = (activityDuration / timelineDuration) * 100
  // 计算时间轴的实际可用宽度（容器宽度减去左侧边栏宽度）
  const timelineWidth = dateRange.value.length * cellWidth.value
  const availableWidth = timelineWidth // 时间轴容器已经通过margin-left定位，不需要额外减去边栏宽度

  const barLeft = (startPercent / 100) * availableWidth
  // 限制最大宽度，防止超长活动条超出容器
  const maxWidth = availableWidth * 1 // 最多占用100%的可用宽度
  const barWidth = Math.min((widthPercent / 100) * availableWidth, maxWidth)

  // 活动网格已经通过margin-left: 200px定位，所以横线位置计算是正确的

  logger.debug(`📏 [样式计算] 位置计算:`, {
    timelineStart: timelineStartTime.toLocaleString('zh-CN'),
    timelineEnd: timelineEndTime.toLocaleString('zh-CN'),
    visibleStart: new Date(visibleStart).toLocaleString('zh-CN'),
    visibleEnd: new Date(visibleEnd).toLocaleString('zh-CN'),
    startPercent: startPercent.toFixed(2) + '%',
    widthPercent: widthPercent.toFixed(2) + '%',
    timelineWidth: timelineWidth.toFixed(2) + 'px',
    availableWidth: availableWidth.toFixed(2) + 'px',
    barLeft: barLeft.toFixed(2) + 'px',
    barWidth: barWidth.toFixed(2) + 'px',
    maxWidth: maxWidth.toFixed(2) + 'px'
  })

  // 计算垂直位置，避免重叠
  const barHeight = 18
  const barSpacing = 2
  const topOffset = 5 + (activityIndex * (barHeight + barSpacing))

  return {
    backgroundColor: activityColorMap.value[activity.camp_name] || '#888888',
    left: `${barLeft-200}px`,
    width: `${Math.max(5, barWidth)}px`, // 最小宽度5px
    height: barHeight + 'px',
    position: 'absolute',
    top: topOffset + 'px',
    borderRadius: '3px',
    border: '1px solid rgba(255, 255, 255, 0.4)',
    cursor: 'pointer',
    zIndex: 10 + activityIndex,
    transition: 'all 0.2s ease'
  }
}

const getActivityTooltip = (activity: any) => {
  const startTime = new Date(activity.start_time * 1000).toLocaleString('zh-CN')
  const endTime = new Date(activity.end_time * 1000).toLocaleString('zh-CN')
  const duration = Math.ceil((activity.end_time - activity.start_time) / 86400)
  
  return `${activity.camp_name}\n开始: ${startTime}\n结束: ${endTime}\n持续: ${duration}天`
}

const showActivityDetail = (activity: any) => {
  emit('activity-click', activity)
  ElMessage.info(`点击了活动: ${activity.camp_name} (区服: ${activity.server})`)
}

const toggleActivityVisibility = (campName: string) => {
  const index = hiddenActivities.value.indexOf(campName)
  if (index > -1) {
    // 如果活动已被隐藏，移除隐藏状态
    hiddenActivities.value.splice(index, 1)
    ElMessage.success(`显示活动: ${campName}`)
  } else {
    // 如果活动未被隐藏，添加隐藏状态
    hiddenActivities.value.push(campName)
    ElMessage.info(`隐藏活动: ${campName}`)
  }
}




// 监听数据变化
watch([() => props.campData, () => props.selectedServers], () => {
  logger.debug('🔄 [时间线] 数据更新:', {
    活动数量: props.campData?.length || 0,
    选中服务器: props.selectedServers?.length || 0
  })
}, { deep: true })

onMounted(() => {
  logger.debug('📅 [时间线] 组件已挂载')
})
</script>

<style scoped>
.activity-timeline {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: transparent;
}

.timeline-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(0, 0, 0, 0.2);
  z-index: 100;
}

.timeline-icon {
  color: #409eff;
  font-size: 20px;
}

.timeline-title {
  font-size: 18px;
  font-weight: bold;
  color: #ffffff;
  flex: 1;
}


.timeline-content {
  position: relative;
  overflow: auto;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  margin: 20px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.timeline-wrapper {
  position: relative;
  width: fit-content;
  min-width: 100%;
}

/* 固定头部区域 */
.fixed-headers {
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  z-index: 50;
  display: flex;
  background: rgba(0, 0, 0, 0.9);
  backdrop-filter: blur(10px);
}

.corner-header {
  width: 200px;
  height: 60px;
  background: rgba(0, 0, 0, 0.9);
  backdrop-filter: blur(10px);
  border-right: 1px solid rgba(255, 255, 255, 0.1);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 60;
}

.corner-label {
  font-size: 12px;
  color: #ccc;
  font-weight: bold;
}

.date-header {
  display: flex;
  background: rgba(0, 0, 0, 0.9);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  overflow: hidden;
}

.date-cell {
  border-right: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.02);
  transition: background-color 0.2s;
  flex-shrink: 0;
}

.date-cell.today {
  background: rgba(64, 158, 255, 0.2);
  border-color: rgba(64, 158, 255, 0.5);
}

.date-main {
  font-size: 16px;
  font-weight: bold;
  color: #ffffff;
}

.date-sub {
  font-size: 12px;
  color: #ccc;
  margin-top: 2px;
}

/* 滚动内容区域 */
.scroll-content {
  display: flex;
}

.servers-sidebar {
  position: sticky;
  left: 0;
  width: 200px;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(5px);
  border-right: 1px solid rgba(255, 255, 255, 0.1);
  z-index: 40;
}

.server-info {
  padding-left: 12px;
  display: flex;
  align-items: center;
  gap: 12px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  transition: background-color 0.2s;
}

.server-info:hover {
  background: rgba(255, 255, 255, 0.05);
}

.server-square {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-weight: bold;
  font-size: 12px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  flex-shrink: 0;
}

.server-details {
  flex: 1;
  min-width: 0;
}

.server-name {
  font-size: 13px;
  font-weight: bold;
  color: #ffffff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.server-meta {
  font-size: 10px;
  color: #999;
  margin-top: 2px;
}

.server-activities {
  font-size: 10px;
  color: #67c23a;
  margin-top: 1px;
}

/* 活动网格 */
.activity-grid {
  position: relative;
  margin-left: 200px;
}

.server-row {
  position: relative;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.activity-cell {
  position: absolute;
  border-right: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(255, 255, 255, 0.01);
  transition: background-color 0.2s;
}

.activity-cell.today {
  background: rgba(64, 158, 255, 0.05);
}

.activity-cell:hover {
  background: rgba(255, 255, 255, 0.05);
}

.activity-bar {
  transition: all 0.2s ease;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

.activity-bar:hover {
  transform: scale(1.05);
  z-index: 100 !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
}

.activity-name {
  font-size: 10px;
  color: #ffffff;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.8);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 6px;
  line-height: 18px;
  display: block;
}

/* 使用浏览器原生滚动条样式 */
.timeline-content::-webkit-scrollbar {
  width: 12px;
  height: 12px;
}

.timeline-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 6px;
}

.timeline-content::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.4);
  border-radius: 6px;
  transition: background-color 0.2s;
}

.timeline-content::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.6);
}

.timeline-content::-webkit-scrollbar-corner {
  background: rgba(255, 255, 255, 0.1);
}

/* 空状态 */
.empty-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
}

/* 图例 */
.timeline-legend {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  padding: 16px;
  margin: 20px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.legend-title {
  font-size: 14px;
  font-weight: bold;
  color: #ffffff;
  margin-bottom: 12px;
  text-align: center;
}

.legend-items {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 4px;
  transition: background-color 0.2s;
  cursor: pointer;
}

.legend-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.legend-item.hidden-activity {
  opacity: 0.4;
  background: rgba(255, 0, 0, 0.1);
  cursor: pointer;
}

.legend-item.hidden-activity:hover {
  opacity: 0.7;
  background: rgba(255, 0, 0, 0.2);
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.legend-text {
  font-size: 12px;
  color: #ccc;
  white-space: nowrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .timeline-header {
    flex-direction: column;
    gap: 8px;
    align-items: stretch;
  }
  
  .timeline-title {
    text-align: center;
  }
  
  
  .corner-header,
  .servers-sidebar {
    width: 150px;
  }
  
  .activity-grid {
    margin-left: 150px;
  }
  
  .server-square {
    width: 24px;
    height: 24px;
    font-size: 10px;
  }
  
  .server-name {
    font-size: 11px;
  }
  
  .server-meta,
  .server-activities {
    font-size: 9px;
  }
}
</style>
